<style lang="less">
@import "../../../styles/common.less";
@import "./snippet-publish.less";
.generator-code{
  border:3px solid #019875;
  border-radius: 5px;
  padding:5px 10px;
}
</style>

<template>
    <div>
        <Row>
            <Col span="18">
                <Card>
                    <Form :label-width="80">
                        <FormItem label="标题" :error="articleError">
                            <Input v-model="form.title" @on-blur="handleArticletitleBlur" placeholder="快捷作用名称" icon="android-list"/>
                        </FormItem>
                        <FormItem label="prefix" :error="articleError">
                            <Input v-model="form.prefix"  placeholder="Snippet快捷提示命令..."/>
                        </FormItem>
                        <FormItem label="print" :error="articleError">
                            <Input v-model="form.print" placeholder="print console code" icon="android-list"/>
                        </FormItem>
                        <FormItem label="body" :error="articleError">
                            <Input v-model="form.code_dev" @on-change="handleCodeBodyHander" type="textarea" :rows="15" placeholder="粘贴代码..."/>
                        </FormItem>
                        <FormItem label="生成代码">
                          <div class="generator-code">
                             {{form.code_body||'无'}}
                           </div>
                        </FormItem>
                    </Form>
                    
                </Card>
            </Col>
            <Col span="6" class="padding-left-10">
                <Card>
                    <p slot="title">
                        <Icon type="paper-airplane"></Icon>
                        发布
                    </p>
                    <Row class="margin-top-20 publish-button-con">
                        <!-- <span class="publish-button"><Button @click="handleSaveDraft">保存草稿</Button></span>
                        <span class="publish-button"><Button @click="handleSaveDraft">复制</Button></span> -->
                        <span class="publish-button"><Button @click="handlePublish" :loading="publishLoading" icon="ios-checkmark" style="width:90px;" type="primary">发布</Button></span>
                    </Row>
                </Card>
                <div class="margin-top-10">
                    <Card>
                        <p slot="title">
                            <Icon type="navicon-round"></Icon>
                            分类目录
                        </p>
                        <Tabs type="card">
                            <TabPane label="所有分类目录">
                                <div class="classification-con">
                                    <Tree :data="classificationList" @on-select-change="setClassificationInAll"></Tree>
                                </div>
                            </TabPane>
                            <TabPane label="常用目录">
                                <div class="classification-con">
                                    <CheckboxGroup v-model="offenUsedClassSelected" @on-change="setClassificationInOffen">
                                        <p v-for="item in offenUsedClass" :key="item.title">
                                            <Checkbox :label="item.title">{{ item.title }}</Checkbox>
                                        </p>
                                    </CheckboxGroup>
                                </div>
                            </TabPane>
                        </Tabs>
                    </Card>
                </div>
                <div class="margin-top-10">
                    <Card>
                        <p slot="title">
                            <Icon type="ios-pricetags-outline"></Icon>
                            标签
                        </p>
                        <Row>
                            <Col span="18">
                                <Select v-model="articleTagSelected" multiple @on-change="handleSelectTag" placeholder="请选择Snippet标签">
                                    <Option v-for="item in articleTagList" :value="item.value" :key="item.value">{{ item.value }}</Option>
                                </Select>
                            </Col>
                            <Col span="6" class="padding-left-10">
                                <Button v-show="!addingNewTag" @click="handleAddNewTag" long type="ghost">新建</Button>
                            </Col>
                        </Row>
                        <transition name="add-new-tag">
                            <div v-show="addingNewTag" class="add-new-tag-con">
                                <Col span="14">
                                    <Input v-model="newTagName" placeholder="请输入标签名" />                                
                                </Col>
                                <Col span="5" class="padding-left-10">
                                    <Button @click="createNewTag" long type="primary">确定</Button>
                                </Col>
                                <Col span="5" class="padding-left-10">
                                    <Button @click="cancelCreateNewTag" long type="ghost">取消</Button>
                                </Col>
                            </div>
                        </transition>
                    </Card>
                </div>
            </Col>
        </Row>

    </div>
</template>

<script>
import API from '../../../api/api_snippet';
import SAPI from '../../../api/api_snippet_category';
export default {
  name: "snippet-publish",
  data() {
    return {
      form: {
        title: "",
        prefix: "",
        code_body: "",
        code_dev: "",
        print: "",
        lang:'javascript',
        cid: 999 // 无分类
      },
      articleError: "",
      articleStateList: [{ value: "草稿" }, { value: "等待复审" }],
      editOpenness: false,
      Openness: "公开",
      currentOpenness: "公开",
      topArticle: false,
      publishTime: "",
      publishTimeType: "immediately",
      editPublishTime: false, // 是否正在编辑发布时间
      articleTagSelected: [], // Snippet选中的标签
      articleTagList: [], // 所有标签列表
      classificationList: [],
      classificationSelected: [], // 在所有分类目录中选中的目录数组
      offenUsedClass: [],
      offenUsedClassSelected: [], // 常用目录选中的目录
      classificationFinalSelected: [], // 最后实际选择的目录
      publishLoading: false,
      addingNewTag: false, // 添加新标签
      newTagName: "" // 新建标签名
    };
  },
  methods: {

    handleCodeBodyHander(){
      let result = this._getDmSnippet(this.form.code_dev);
      this.form.code_body = result;
    },
    _getDmSnippet(str) {
        str = str.replace(/\$/g,"\\\\$");
        str = str.replace(/\n/g, "\\n");
        str = str.replace(/    /g, "\\t");
        str = str.replace(/[	]/g, "\\t");
        // str = str.replace(/\\n(\s+)/g, function (reg, $1) {
        //     return "\\n" + $1.replace(/\s\s\s\s/g, "\\t")
        // });
        // 双引号全部替换为实体
        str = str.replace(/\"/g, '\\"');
        return str;
    },
    _getCategoryList() {
      let params = {};
      SAPI.tree(params).then(res => {
         this.classificationList = res.map((item, index)=>{
              item['expand'] = true;
              return item;
          });
      });
    },
    handleArticletitleBlur() {
      if (this.form.title.length !== 0) {
        // this.articleError = '';
        localStorage.form.title = this.form.title; // 本地存储Snippet标题
      } else {
        // this.articleError = 'Snippet标题不可为空哦';
        this.$Message.error("Snippet标题不可为空哦");
      }
    },
    editArticlePath() {
      this.editLink = !this.editLink;
      this.editPathButtonType =
        this.editPathButtonType === "ghost" ? "success" : "ghost";
      this.editPathButtonText =
        this.editPathButtonText === "编辑" ? "完成" : "编辑";
    },
    handleEditOpenness() {
      this.editOpenness = !this.editOpenness;
    },
    handleSaveOpenness() {
      this.Openness = this.currentOpenness;
      this.editOpenness = false;
    },
    cancelEditOpenness() {
      this.currentOpenness = this.Openness;
      this.editOpenness = false;
    },
    handleEditPublishTime() {
      this.editPublishTime = !this.editPublishTime;
    },
    handleSavePublishTime() {
      this.publishTimeType = "timing";
      this.editPublishTime = false;
    },
    cancelEditPublishTime() {
      this.publishTimeType = "immediately";
      this.editPublishTime = false;
    },
    setPublishTime(datetime) {
      this.publishTime = datetime;
    },
    setClassificationInAll(selectedArray) {
        let obj = selectedArray[0];
        if(obj.children.length === 0){
            this.form.cid = obj.id;
            this.form.lang = obj.name;
            console.log(this.classificationFinalSelected,selectedArray);
        }
    //   this.classificationFinalSelected = selectedArray.map(item => {
    //     return item.title;
    //   });
    //   console.log(selectedArray, this.classificationFinalSelected,8888888888);
    //   localStorage.classificationSelected = JSON.stringify(
    //     this.classificationFinalSelected
    //   ); // 本地存储所选目录列表
    },
    setClassificationInOffen(selectedArray) {
      this.classificationFinalSelected = selectedArray;
    },
    handleAddNewTag() {
      this.addingNewTag = !this.addingNewTag;
    },
    createNewTag() {
      if (this.newTagName.length !== 0) {
        this.articleTagList.push({ value: this.newTagName });
        this.addingNewTag = false;
        setTimeout(() => {
          this.newTagName = "";
        }, 200);
      } else {
        this.$Message.error("请输入标签名");
      }
    },
    cancelCreateNewTag() {
      this.newTagName = "";
      this.addingNewTag = false;
    },
    canPublish() {
      if (this.form.title.length === 0) {
        this.$Message.error("请输入Snippet标题");
        return false;
      } else {
        return true;
      }
    },
    handlePreview() {
      if (this.canPublish()) {
        if (this.publishTimeType === "immediately") {
          let date = new Date();
          let year = date.getFullYear();
          let month = date.getMonth() + 1;
          let day = date.getDate();
          let hour = date.getHours();
          let minute = date.getMinutes();
          let second = date.getSeconds();
          localStorage.publishTime =
            year +
            " 年 " +
            month +
            " 月 " +
            day +
            " 日 -- " +
            hour +
            " : " +
            minute +
            " : " +
            second;
        } else {
          localStorage.publishTime = this.publishTime; // 本地存储发布时间
        }

        this.$router.push({
          name: "preview"
        });
      }
    },
    handleSaveDraft() {
      if (!this.canPublish()) {
        //
      }
    },
    handlePublish() {
      if (this.canPublish()) {
        this.publishLoading = true;
        let params = this.form;
        API.add(params).then((res)=>{
            this.publishLoading = false;
            console.log(res,66666);
            this.$Notice.success({
              title: "保存成功",
              desc: "Snippet《" + this.form.title + "》保存成功"
            });
        });
        // setTimeout(() => {
        //   this.publishLoading = false;
        //   this.$Notice.success({
        //     title: "保存成功",
        //     desc: "Snippet《" + this.form.title + "》保存成功"
        //   });
        // }, 1000);
      }
    },
    handleSelectTag() {
      localStorage.tagsList = JSON.stringify(this.articleTagSelected); // 本地存储Snippet标签列表
    }
  },
  computed: {},

  mounted() {
    // 获取分类
    this._getCategoryList();
    this.articleTagList = [
      { value: "vue" },
      { value: "iview" },
      { value: "ES6" },
      { value: "webpack" },
      { value: "babel" },
      { value: "eslint" }
    ];
    this.classificationList = [
      {
        title: "Vue实例",
        expand: true,
        children: [
          {
            title: "数据与方法",
            expand: true
          },
          {
            title: "生命周期",
            expand: true
          }
        ]
      },
      {
        title: "Class与Style绑定",
        expand: true,
        children: [
          {
            title: "绑定HTML class",
            expand: true,
            children: [
              {
                title: "对象语法",
                expand: true
              },
              {
                title: "数组语法",
                expand: true
              },
              {
                title: "用在组件上",
                expand: true
              }
            ]
          },
          {
            title: "生命周期",
            expand: true
          }
        ]
      },
      {
        title: "模板语法",
        expand: true,
        children: [
          {
            title: "插值",
            expand: true
          },
          {
            title: "指令",
            expand: true
          },
          {
            title: "缩写",
            expand: true
          }
        ]
      }
    ];
    this.offenUsedClass = [
      {
        title: "vue实例"
      },
      {
        title: "生命周期"
      },
      {
        title: "模板语法"
      },
      {
        title: "插值"
      },
      {
        title: "缩写"
      }
    ];
  },
  destroyed() {

  }
};
</script>
